package com.deanlib.cabinet.ui.view;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;

import com.arthenica.ffmpegkit.FFmpegKitConfig;
import com.deanlib.cabinet.R;
import com.deanlib.cabinet.app.Constants;
import com.deanlib.cabinet.base.BaseActivity;
import com.deanlib.cabinet.data.event.MessageEvent;
import com.deanlib.cabinet.data.event.UserStateEvent;
import com.deanlib.cabinet.data.network.NetWorkManager;
import com.deanlib.cabinet.databinding.ActivityMainBinding;
import com.deanlib.cabinet.service.MainService;
import com.deanlib.cabinet.service.sync2.ShadowWorker;
import com.deanlib.cabinet.ui.Navigation;
import com.deanlib.cabinet.ui.view.photo.LocalPhotoListFragment;
import com.deanlib.cabinet.ui.view.photo.PhotoList3Fragment;
import com.deanlib.cabinet.ui.view.photo.PhotoListFragment;
import com.deanlib.cabinet.ui.view.search.SearchFragment;
import com.deanlib.cabinet.utils.ConfigManager;
import com.deanlib.cabinet.utils.UserManager;
import com.deanlib.cabinet.utils.OssManager;
import com.elvishew.xlog.XLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class MainActivity extends BaseActivity<ActivityMainBinding> {

//    PhotoListFragment photoListFragment;
//    LocalPhotoListFragment localPhotoListFragment;
    PhotoList3Fragment photoList3Fragment;
    SearchFragment searchFragment;
    Disposable subscribeMessageUiGone;
    Fragment currentFragment;


    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void eventUserState(UserStateEvent event){
//        if (UserManager.getInstance().isLogin() && currentFragment instanceof LocalPhotoListFragment){
//            currentFragment = photoListFragment;
//            getSupportFragmentManager().beginTransaction().
//                    replace(R.id.layoutContainer, currentFragment).commit();
//        }
//        if (!UserManager.getInstance().isLogin() && currentFragment instanceof PhotoListFragment){
//            currentFragment = localPhotoListFragment;
//            getSupportFragmentManager().beginTransaction().
//                    replace(R.id.layoutContainer, currentFragment).commit();
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventMessage(MessageEvent event){
        if (event.type == MessageEvent.TYPE_MESSAGE) {
            if (subscribeMessageUiGone!=null && !subscribeMessageUiGone.isDisposed()){
                subscribeMessageUiGone.dispose();
            }
            binding.tvMessage.setVisibility(View.VISIBLE);
            binding.tvMessage.setText(event.message);
            subscribeMessageUiGone = Observable.timer(3, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread()).subscribe(l -> {
                binding.tvMessage.setVisibility(View.GONE);
            });
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
//        photoListFragment = new PhotoListFragment();
//        localPhotoListFragment = new LocalPhotoListFragment();
        photoList3Fragment = new PhotoList3Fragment();
        searchFragment = new SearchFragment();

//        ContentResolver.setSyncAutomatically(SyncAdapter.getSyncAccount(this),
//                getString(R.string.content_authority), true);


    }

//    private Fragment getPhotoListFragment(){
//        Fragment fragment;
//        if (UserManager.getInstance().isLogin()){
//            fragment = photoListFragment;
//        }else {
//            fragment = localPhotoListFragment;
//        }
//        return fragment;
//    }

    @Override
    public void initView() {
        binding.layoutBottomNavigation.setOnNavigationItemSelectedListener(item -> {
            if (item.getItemId() == R.id.photo) {
//                currentFragment = getPhotoListFragment();
                currentFragment = photoList3Fragment;
            } else if (item.getItemId() == R.id.search) {
                currentFragment = searchFragment;
            }
            getSupportFragmentManager().beginTransaction().
                    replace(R.id.layoutContainer, currentFragment).commit();
            return true;
        });
        binding.imgUserAvatar.setOnClickListener(view -> {
            if (UserManager.getInstance().isLogin()) {
                Navigation.toUser(this);
            } else {
                Navigation.toLogin(this);
            }
//            SyncAdapter.syncImmediately(this);
        });
        getSupportFragmentManager().beginTransaction().
                replace(R.id.layoutContainer, photoList3Fragment).commit();
    }

    @Override
    public void loadData() {
        FFmpegKitConfig.enableLogCallback(log -> {
            if (log!=null && !TextUtils.isEmpty(log.getMessage())){
                XLog.d("FFMPEG-LOG", log.getMessage());
            }
        });
        loadConfig();
        shadowWork();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Navigation.CODE_LOGIN && resultCode == RESULT_OK) {
            loadConfig();
            shadowWork();
        }
    }

    /**
     * 获取系统的配置信息
     */
    private void loadConfig() {
        if (UserManager.getInstance().isLogin()) {
            if (ConfigManager.getInstance().getOssKey() == null) {
                request(NetWorkManager.getRequest().getConfigKeyOss(), optional -> {
                    if (optional.isPresent()) {
                        ConfigManager.getInstance().setOssKey(optional.get());
                        OssManager.getInstance().asyncInitOSS();
                    }
                });
            }else {
                OssManager.getInstance().asyncInitOSS();
            }
        }

    }



    /**
     * 开启 workmanager 用于资源收集和上传
     */
    private void shadowWork() {
        WorkManager.getInstance(this).cancelAllWork();
        if (ConfigManager.getInstance().isAllowUpload()) {
            Constraints constraints = new Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.UNMETERED)
                    .build();
            WorkRequest request = new PeriodicWorkRequest.Builder(ShadowWorker.class, Constants.UPLOAD_WORKER_REPEAT_INTERVAL, TimeUnit.MILLISECONDS)
                    .setConstraints(constraints).build();
            WorkManager.getInstance(this).enqueue(request);
        }
    }
}